<template>
    <div>
        <ul class="list">
            <li class="item" v-for="(item,index) in letters" @click="handleClick" :key="item" :ref="item"
                @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd">{{item}}</li>
        </ul>
    </div>
</template>
  
<script>

export default {
    name: "CityAlphabet",
    props: ['cities'],
    data() {
        return {
            touchStatus: false,
            startY: 0,
            timer: null,
        }
    },
    computed: {
        letters() {
            const letters = [];
            for (let i in this.cities) {
                letters.push(i);
            }
            return letters;
        }
    },
    updated() {
        this.startY = this.$refs['A'][0].offsetTop; // 元素A距离页面顶部的距离(因为没父元素,默认为距离body的距离)
    },
    methods: {
        handleClick(e) {
            // console.log(e.target.innerText);
            this.$emit("change", e.target.innerText);
        },
        handleTouchStart() {
            this.touchStatus = true;
        },
        handleTouchMove(e) {
            if (this.touchStatus) {
                if (this.timer) {
                    clearTimeout(this.timer);
                }
                this.timer = setTimeout(() => {
                    const touchY = e.touches[0].clientY - 79; // 当前鼠标触摸位置距离页面顶部的距离
                    const index = Math.floor((touchY - this.startY) / 27); // 二者相减就是元素A距离当前触摸位置的距离,而每个元素都有高度,除以这个数字,就能知道当前触摸的字母是哪个

                    if (index >= 0 && index <= this.letters.length) {
                        this.$emit("change", this.letters[index]);
                    }
                },6);
            }
        },
        handleTouchEnd() {
            this.touchStatus = false;
        }
    }
}
</script>
  
<style scoped>
.list {
    display: flex;
    flex-direction: column;
    justify-content: center;
    position: absolute;
    top: 1.58rem;
    right: 0;
    bottom: 0;
    width: .4rem;
    /*background-color: red;*/
}

.list .item {
    text-align: center;
    line-height: .54rem;

    color: #00bcd4;
}
</style>